<template>
  <div class="inventory-page">
    <div class="page-header">
      <h2>商品管理</h2>
      <button @click="showAddModal = true" class="add-btn">
        <span>+</span> 添加商品
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-input">
        <input
          v-model="searchKeyword"
          placeholder="搜索商品名称或编码"
          class="search-field"
        />
        <button @click="searchProducts" class="search-btn">搜索</button>
      </div>
      <div class="filter-options">
        <select v-model="categoryFilter" class="filter-select">
          <option value="">全部分类</option>
          <option value="饮料">饮料</option>
          <option value="零食">零食</option>
          <option value="日用品">日用品</option>
        </select>
        <select v-model="stockFilter" class="filter-select">
          <option value="">全部库存</option>
          <option value="in">有库存</option>
          <option value="low">库存不足</option>
          <option value="out">缺货</option>
        </select>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="products-grid">
      <div
        v-for="product in pageData.data"
        :key="product.id"
        class="product-card"
      >
        <div class="product-image">
          <img :src="product.image || '/default-product.png'" :alt="product.name" />
          <div class="stock-badge" :class="getStockClass(product.stock)">
            {{ getStockText(product.stock) }}
          </div>
        </div>
        <div class="product-info">
          <h3 class="product-name">{{ product.name }}</h3>
          <div class="product-code">编码：{{ product.code }}</div>
          <div class="product-category">分类：{{ product.category }}</div>
          <div class="product-price">¥{{ product.price.toFixed(2) }}</div>
          <div class="product-stock">库存：{{ product.stock }} 件</div>
        </div>
        <div class="product-actions">
          <button @click="editProduct(product)" class="edit-btn">编辑</button>
          <button @click="adjustStock(product)" class="stock-btn">库存</button>
          <button @click="deleteProduct(product.id)" class="delete-btn">删除</button>
        </div>
      </div>
    </div>
    <div class="page">
      <el-pagination background :current-page="searchObject.no" :page-sizes="[10, 20, 50, 100]"
                     :page-size="pageData.size" :pager-count="5"
                     layout="total, sizes, prev, pager, next, jumper" :page-count="pageData.totalPage"
                     :total="pageData.total" @size-change="sizeChange" @current-change="pageChange">
      </el-pagination>
    </div>

    <!-- 添加/编辑商品弹窗 -->
    <div v-if="showAddModal || showEditModal" class="modal">
      <div class="modal-content">
        <h3>{{ showEditModal ? '编辑商品' : '添加商品' }}</h3>
        <form @submit.prevent="saveProduct" class="product-form">
          <div class="form-group">
            <label>商品名称</label>
            <input v-model="editingProduct.name" required class="form-input" />
          </div>
          <div class="form-group">
            <label>商品编码</label>
            <input v-model="editingProduct.code" required class="form-input" />
          </div>
          <div class="form-group">
            <label>分类</label>
            <select v-model="editingProduct.category" required class="form-select">
              <option value="饮料">饮料</option>
              <option value="零食">零食</option>
              <option value="日用品">日用品</option>
            </select>
          </div>
          <div class="form-group">
            <label>价格</label>
            <input
              v-model="editingProduct.price"
              type="number"
              step="0.01"
              required
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label>库存</label>
            <input
              v-model="editingProduct.stock"
              type="number"
              required
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label>商品图片URL</label>
            <input v-model="editingProduct.image" class="form-input" />
          </div>
          <div class="form-actions">
            <button type="submit" class="save-btn">保存</button>
            <button type="button" @click="closeModal" class="cancel-btn">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 库存调整弹窗 -->
    <div v-if="showStockModal" class="modal">
      <div class="modal-content">
        <h3>调整库存</h3>
        <div class="stock-info">
          <p>商品：{{ selectedProduct?.name }}</p>
          <p>当前库存：{{ selectedProduct?.stock }} 件</p>
        </div>
        <div class="stock-adjustment">
          <label>调整数量：</label>
          <input
            v-model="stockAdjustment"
            type="number"
            class="form-input"
            placeholder="正数为增加，负数为减少"
          />
        </div>
        <div class="form-actions">
          <button @click="confirmStockAdjustment" class="save-btn">确认</button>
          <button @click="showStockModal = false" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import {usePageData} from "@/uses/usePageData.js";
import {defineStore} from "pinia";

// 响应式数据
const searchKeyword = ref('')
const categoryFilter = ref('')
const stockFilter = ref('')
const showAddModal = ref(false)
const showEditModal = ref(false)
const showStockModal = ref(false)
const selectedProduct = ref(null)
const stockAdjustment = ref(0)


const searchStore = defineStore('productStore', {

  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 8,
        sortField: "id",
        sortMethod: "desc",
        shop: '',
        name: '',
        productCatalog: '',
        productGroup: ''
      }
    }
  }
})

const {searchObject} = searchStore();

const {pageData, sizeChange, pageChange, search, changeTableSort, loading} = usePageData("product_list", searchObject);

// 编辑中的商品数据
const editingProduct = ref({
  name: '',
  code: '',
  category: '饮料',
  price: 0,
  stock: 0,
  image: ''
})

// 模拟商品数据
const products = ref([
  {
    id: 1,
    name: '可口可乐 330ml',
    code: '001',
    category: '饮料',
    price: 3.50,
    stock: 100,
    image: '/coke.png'
  },
  {
    id: 2,
    name: '百事可乐 330ml',
    code: '002',
    category: '饮料',
    price: 3.50,
    stock: 80,
    image: '/pepsi.png'
  },
  {
    id: 3,
    name: '雪碧 330ml',
    code: '003',
    category: '饮料',
    price: 3.00,
    stock: 90,
    image: '/sprite.png'
  },
  {
    id: 4,
    name: '薯片 原味',
    code: '004',
    category: '零食',
    price: 8.50,
    stock: 50,
    image: '/chips.png'
  },
  {
    id: 5,
    name: '红牛 250ml',
    code: '005',
    category: '饮料',
    price: 6.50,
    stock: 30,
    image: '/redbull.png'
  },
  {
    id: 6,
    name: '牙膏 薄荷味',
    code: '006',
    category: '日用品',
    price: 12.00,
    stock: 0,
    image: '/toothpaste.png'
  }
])

// 计算属性
const filteredProducts = computed(() => {
  let filtered = products.value

  // 关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(product =>
      product.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      product.code.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  // 分类筛选
  if (categoryFilter.value) {
    filtered = filtered.filter(product => product.category === categoryFilter.value)
  }

  // 库存筛选
  if (stockFilter.value) {
    filtered = filtered.filter(product => {
      switch (stockFilter.value) {
        case 'in':
          return product.stock > 10
        case 'low':
          return product.stock <= 10 && product.stock > 0
        case 'out':
          return product.stock === 0
        default:
          return true
      }
    })
  }

  return filtered
})

// 方法
const searchProducts = () => {
  // 搜索功能已通过计算属性实现
}

const getStockClass = (stock) => {
  if (stock === 0) return 'out-of-stock'
  if (stock <= 10) return 'low-stock'
  return 'in-stock'
}

const getStockText = (stock) => {
  if (stock === 0) return '缺货'
  if (stock <= 10) return '库存不足'
  return '有库存'
}

const editProduct = (product) => {
  editingProduct.value = { ...product }
  showEditModal.value = true
}

const adjustStock = (product) => {
  selectedProduct.value = product
  stockAdjustment.value = 0
  showStockModal.value = true
}

const deleteProduct = (productId) => {
  if (confirm('确定要删除这个商品吗？')) {
    const index = products.value.findIndex(p => p.id === productId)
    if (index > -1) {
      products.value.splice(index, 1)
    }
  }
}

const saveProduct = () => {
  if (showEditModal.value) {
    // 编辑现有商品
    const index = products.value.findIndex(p => p.id === editingProduct.value.id)
    if (index > -1) {
      products.value[index] = { ...editingProduct.value }
    }
  } else {
    // 添加新商品
    const newProduct = {
      ...editingProduct.value,
      id: Date.now() // 简单的ID生成
    }
    products.value.push(newProduct)
  }

  closeModal()
}

const confirmStockAdjustment = () => {
  if (selectedProduct.value) {
    const index = products.value.findIndex(p => p.id === selectedProduct.value.id)
    if (index > -1) {
      products.value[index].stock += parseInt(stockAdjustment.value) || 0
      if (products.value[index].stock < 0) {
        products.value[index].stock = 0
      }
    }
  }
  showStockModal.value = false
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingProduct.value = {
    name: '',
    code: '',
    category: '饮料',
    price: 0,
    stock: 0,
    image: ''
  }
}
</script>

<style scoped>

.page{
  margin-top: 10px;
}
.inventory-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-btn:hover {
  background: #337ecc;
}

.add-btn span {
  font-size: 20px;
  font-weight: bold;
}

/* 搜索和筛选 */
.search-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.search-input {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.search-field {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.search-field:focus {
  border-color: #409eff;
}

.search-btn {
  padding: 12px 24px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
}

.filter-options {
  display: flex;
  gap: 16px;
}

.filter-select {
  padding: 10px 16px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  background: white;
}

/* 商品网格 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.product-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.product-card:hover {
  transform: translateY(-4px);
}

.product-image {
  position: relative;
  width: 100%;
  height: 200px;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.stock-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.stock-badge.in-stock {
  background: #67c23a;
}

.stock-badge.low-stock {
  background: #e6a23c;
}

.stock-badge.out-of-stock {
  background: #f56c6c;
}

.product-info {
  margin-bottom: 16px;
}

.product-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.product-code, .product-category {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.product-price {
  font-size: 20px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 8px;
}

.product-stock {
  font-size: 14px;
  color: #909399;
}

.product-actions {
  display: flex;
  gap: 8px;
}

.edit-btn, .stock-btn, .delete-btn {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.edit-btn {
  background: #409eff;
  color: white;
}

.stock-btn {
  background: #67c23a;
  color: white;
}

.delete-btn {
  background: #f56c6c;
  color: white;
}

.edit-btn:hover {
  background: #337ecc;
}

.stock-btn:hover {
  background: #5daf34;
}

.delete-btn:hover {
  background: #e45656;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 30px;
  min-width: 500px;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  color: #303133;
}

.product-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.form-input, .form-select {
  padding: 12px 16px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.form-input:focus, .form-select:focus {
  border-color: #409eff;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.save-btn, .cancel-btn {
  flex: 1;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
}

.save-btn {
  background: #409eff;
  color: white;
}

.cancel-btn {
  background: #f56c6c;
  color: white;
}

/* 库存调整弹窗 */
.stock-info {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.stock-info p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #606266;
}

.stock-adjustment {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 20px;
}

.stock-adjustment label {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .inventory-page {
    padding: 15px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-input {
    flex-direction: column;
  }

  .filter-options {
    flex-direction: column;
  }

  .products-grid {
    grid-template-columns: 1fr;
  }

  .modal-content {
    min-width: 90%;
    margin: 20px;
  }

  .product-actions {
    flex-direction: column;
  }
}
</style>
